package com.heima.admin.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1、检查参数
        if (StringUtils.isEmpty(dto.getName())&&StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //2、根据用户名查询用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,dto.getName()));
        if (adUser!=null){
            String password = dto.getPassword();
            String salt = adUser.getSalt();
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
            if (pwd.equals(adUser.getPassword())){//密码正确，返回token
                Map<String,Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                //将密码和盐清空
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {//密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
    }
}
